package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {
    //毫秒，这里2分钟有效
    private static long tokenExpiration = 2*60*1000;
    //自定义秘钥
    private static String tokenSignKey = "123456";
    public static String createToken(String userName, String password) {
        String token = Jwts.builder()
                //设置分组
                .setSubject("YYGH-USER")
                //设置字符串过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //私有部分
                .claim("userName", userName)
                .claim("password", password)
                //设置秘钥
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    /**
     * 解析JWT
     *
     * @param jwt
     * @return
     */
    public static Claims parseJWT(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(jwt).getBody();
        return claims;
    }
}
